package com.manager.devicemanager.config;

import com.alibaba.fastjson2.JSONObject;
import com.manager.devicemanager.annotation.OperateLog;
import com.manager.devicemanager.common.OperationTypeEnum;
import com.manager.devicemanager.entity.OperationLog;
import com.manager.devicemanager.service.IDeviceInfoService;
import com.manager.devicemanager.service.OperationLogService;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Aspect
@Log4j2
@Component
public class OperateLogAspect {

    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private IDeviceInfoService iDeviceInfoService;

    @Pointcut("@annotation(com.manager.devicemanager.annotation.OperateLog)")
    public void logPointCut() {
    }
    @Autowired
    private JwtUtil jwtUtil;
    @AfterReturning(pointcut = "logPointCut()", returning = "result")
    public void saveOperateLog(JoinPoint joinPoint, Object result) {
        try {


        long beginTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        OperationLog operationLog = new OperationLog();
        OperateLog operateLog = method.getAnnotation(OperateLog.class);
        if (operateLog != null) {
            operationLog.setOperationtype(operateLog.operationType().getCode());
            operationLog.setOperationdesc(operateLog.operationDesc());
        }
        // 从 JWT 中获取用户 ID
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = JwtUtil.getTokenFromRequest(request);
            if (token != null) {
                String userId = JwtUtil.extractUserId(token);
                operationLog.setUserid(userId);
            }
        }
        operationLog.setMethod(method.getName());

        operationLog.setOperationtime(new Date());
        if (operateLog.operationType().getCode().equals(OperationTypeEnum.CONTROL.getCode())) {
            String argsJsonStr = JSONObject.toJSONString(joinPoint.getArgs()[0]);
            JSONObject params = JSONObject.parseObject(argsJsonStr);
            String deviceid = params.getString("deviceid");
            operationLog.setDeviceid(deviceid);
            String type = params.getJSONObject("message").getString("type");
            String batchname = params.getJSONObject("message").getString("batchname");
//            String config = params.getJSONObject("message").getString("config");
            operationLog.setParams(params.getJSONObject("message").toJSONString());
            operationLog.setControltype(type);
            operationLog.setBatchname(batchname);
            operationLog.setOperationdesc(operationLog.getOperationdesc());
        }else {
            operationLog.setParams(JSONObject.toJSONString(joinPoint.getArgs()));
        }

        long endTime = System.currentTimeMillis();
        operationLog.setSpendtime(endTime - beginTime);
        operationLog.setId(UUID.randomUUID().toString().replace("-", ""));

        // 保存日志
        operationLogService.save(operationLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
